package com.example.denglu.servlet;

import com.example.denglu.service.UserService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    
    private boolean isValidPassword(String password) {
        // 检查密码是否同时包含字母和数字，且长度至少为10位
        return password != null && 
               password.length() >= 10 && 
               password.matches(".*[a-zA-Z].*") && 
               password.matches(".*[0-9].*");
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String phone = request.getParameter("phone");
        String username = request.getParameter("username");
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        
        response.setContentType("application/json;charset=utf-8");
        
        // 验证用户名
        if (username == null || username.trim().length() < 3) {
            response.getWriter().write("{\"success\":false,\"message\":\"用户名长度至少3个字符\"}");
            return;
        }
        
        // 先检查手机号是否已注册
        if (UserService.isPhoneRegistered(phone)) {
            response.getWriter().write("{\"success\":false,\"message\":\"该手机号已被注册\"}");
            return;
        }
        
        HttpSession session = request.getSession();
        String savedCode = (String) session.getAttribute(phone + "_code");
        
        // 验证码验证
        if (savedCode == null) {
            response.getWriter().write("{\"success\":false,\"message\":\"验证码已过期，请重新获取\"}");
            return;
        }
        
        if (!savedCode.equals(code)) {
            response.getWriter().write("{\"success\":false,\"message\":\"验证码错误\"}");
            return;
        }
        
        // 添加密码验证
        if (!isValidPassword(password)) {
            response.getWriter().write("{\"success\":false,\"message\":\"密码必须包含字母和数字，且长度至少10位\"}");
            return;
        }
        
        // 注册用户
        boolean isSuccess = UserService.registerUserByPhone(phone, username, password);
        
        if (isSuccess) {
            session.removeAttribute(phone + "_code");
            session.removeAttribute(phone + "_lastSendTime");
        }
        
        response.getWriter().write("{\"success\":" + isSuccess + 
                ",\"message\":\"" + (isSuccess ? "注册成功" : "注册失败") + "\"}");
    }
} 